package com.shenhan.unsafe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author shenhan
 * @create 2020/6/10 16:47
 * @description
 */
public class ListTest {
    /**
     * arraylist多线程下不安全，解决方案：
     * 1、Vector<>
     * 2、Collections工具类  Collections.synchronizedList(new ArrayList<>())
     * 3、写入时复制：copyOrWriteArrayList<>()  COW 优化策略
     * @param args
     */
    public static void main(String[] args) {
//        List<String> list = new ArrayList<>();
        List<String> list = new CopyOnWriteArrayList<>();
        for (int i = 1; i < 10; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 5));
                System.out.println(list);
            }, String.valueOf(i)).start();
        }
    }
}
